package com.semp.gu.config;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.thoughtworks.xstream.XStream;

public class ConfigurationManager implements IConfigurationManager {

	private XStream				xStream;
	private File				configFolder;

	private final static Logger	logger	= LoggerFactory.getLogger(ConfigurationManager.class);

	public ConfigurationManager() {
		xStream = new XStream();
		
		/*
		 * Init props folder
		 */
		String userHome = System.getProperty("user.home");
		File rootFolder = new File(userHome + File.separator + ".gl");
		if (!rootFolder.exists()) {
			rootFolder.mkdir();
			logger.debug("Created {}", rootFolder);
		}
		
		configFolder = new File(rootFolder.getAbsolutePath() + File.separator + "config");
		if (!configFolder.exists()) {
			configFolder.mkdir();
			logger.debug("Created {}", configFolder);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.semp.gu.config.IConfigurationManager#loadConfiguration(java.lang.
	 * String)
	 */
	public AbstractConfiguration loadConfiguration(AbstractConfiguration defaultConfiguration) throws IOException {
		String configName = defaultConfiguration.getConfigName();
		File configurationFile = getConfigurationFile(defaultConfiguration);
		logger.info("Loading configuration {} from {}", configName, configurationFile);
		
		if (configurationFile.exists()) {
			/*
			 * Load configuration
			 */
			return (AbstractConfiguration) xStream.fromXML(new FileReader(configurationFile));
		} else {
			/*
			 * Store configuration
			 */
			logger.debug("AbstractConfiguration file {} not found for config {}, using an storing default configuration", configurationFile, configName);
			storeConfiguration(defaultConfiguration);
			return defaultConfiguration;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.semp.gu.config.IConfigurationManager#storeConfiguration(com.semp.
	 * gu.config.AbstractConfiguration)
	 */
	public void storeConfiguration(AbstractConfiguration configuration) throws IOException {
		File configurationFile = getConfigurationFile(configuration);
		logger.debug("Writing configuration {}", configurationFile);
		xStream.toXML(configuration, new FileWriter(configurationFile));
	}

	private File getConfigurationFile(AbstractConfiguration configuration) {
		return new File(configFolder + File.separator + configuration.getConfigName() + ".xml");
	}
}
